package com.lxq.smartsign.client.ui;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lxq.smartsign.client.R;
import com.lxq.smartsign.client.util.BluetoothListAdapter;
import com.lxq.smartsign.client.util.ClientConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class BluetoothActivity extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    private boolean isEnable;
    List<JSONObject> bluetoothArray;
    private RecyclerView recyclerView;
    private TextView stateV;
    BluetoothListAdapter adapter;
    JSONArray array;
    RequestQueue queue;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);
        recyclerView=findViewById(R.id.bluetooth_list);
        stateV=findViewById(R.id.bluetooth_state);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        // 注册这个 BroadcastReceiver
        queue= Volley.newRequestQueue(this);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter1);
        IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter2);
        bluetoothArray=new ArrayList<>();
        bluetoothArray=new ArrayList<>();
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter==null){
            Toast.makeText(this, "此设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
        }
        isEnable=bluetoothAdapter.isEnabled();
        if (!bluetoothAdapter.isEnabled()){
            bluetoothAdapter.enable();
            stateV.setText("正在打开蓝牙");
        }

        getMonitors();
        adapter=new BluetoothListAdapter(bluetoothArray);
        recyclerView.setAdapter(adapter);
        stateV.setOnClickListener(v->{
            findBluetooth();
            stateV.setText("正在查找卡机");
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void getMonitors(){
        String url= ClientConfig.SERVER_URL+"/get_monitors";
        JsonArrayRequest request=new JsonArrayRequest(Request.Method.GET,url,null,response -> {
            array=response;
            findBluetooth();
        },error -> Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show());
        queue.add(request);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void findBluetooth(){
        bluetoothArray.clear();
        bluetoothAdapter.cancelDiscovery();
        bluetoothAdapter.startDiscovery();
        /*bluetoothAdapter.getBondedDevices().forEach(bluetoothDevice -> {
            JSONObject object=new JSONObject();
            try {
                object.put("name",bluetoothDevice.getName());
                object.put("address",bluetoothDevice.getAddress());
                bluetoothArray.add(object);
                Log.e("已配对",object.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
        BluetoothListAdapter adapter=new BluetoothListAdapter(bluetoothArray);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);*/

    }
    // 创建一个接受 ACTION_FOUND 的 BroadcastReceiver
    private final BroadcastReceiver receiver = new BroadcastReceiver(){

        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            if (action==null)return;
            // 当 Discovery 发现了一个设备
            //Log.e("接收广播",action);

            switch (action) {
                case BluetoothDevice.ACTION_FOUND:
                    // 从 Intent 中获取发现的 BluetoothDevice
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // 将名字和地址放入要显示的适配器中
                    JSONObject item = new JSONObject();
                    try {
                        item.put("name", device.getName() == null ? "未知设备" : device.getName());
                        item.put("address", device.getAddress());
                        bluetoothArray.add(item);
                        Log.e("蓝牙", item.toString());
                        adapter.notifyDataSetChanged();
                        for(int i=0;i<array.length();i++){
                            if (array.optJSONObject(i).optString("bluetoothMAC").equals(device.getAddress())){
                                bluetoothAdapter.cancelDiscovery();
                                stateV.setText("正在打卡");
                                swipe(device.getAddress());
                                return;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    bluetoothAdapter.cancelDiscovery();
                    stateV.setText("查找完成");
                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,10);
                    if (state==12){
                        bluetoothAdapter.startDiscovery();
                        stateV.setText("正在查找卡机");
                    }

                    break;
            }
        }
    };

    private void swipe(String address) throws JSONException {
        String url=ClientConfig.SERVER_URL+"/by_bluetooth";
        JSONObject param=new JSONObject();
        param.put("address",address);
        param.put("deviceId",ClientConfig.ANDROID_ID);
        param.put("userId",ClientConfig.USER_ID);
        param.put("name",ClientConfig.NAME);
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST,url,param,
                response -> {
            stateV.setText(response.optString("msg"));
                    Toast.makeText(this, response.optString("msg"), Toast.LENGTH_SHORT).show();
                },
                error -> Toast.makeText(this, "网络错误", Toast.LENGTH_SHORT).show());
        queue.add(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bluetoothAdapter.cancelDiscovery();
        if (!isEnable){
            bluetoothAdapter.disable();
        }
    }
}
